package com.zbvc.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zbvc.dao.AdminDao;
import com.zbvc.dao.BookDao;
import com.zbvc.dao.impl.AdminDaoImpl;
import com.zbvc.dao.impl.BookDaoImpl;
import com.zbvc.entity.Admin;

/**
 * Servlet implementation class BorrowServlet
 */
@WebServlet(name = "borror", urlPatterns = { "/borrow" })
public class BorrowServlet extends HttpServlet {
	
	private BookDao bookDao = new BookDaoImpl();
	
	private AdminDao adminDao = new AdminDaoImpl();
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BorrowServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String tip = request.getParameter("tip");
		
		// tip=1表示是借阅 
		if(Integer.parseInt(tip) == 1) {
			int bid = Integer.parseInt(request.getParameter("bid"));
			// 从session里获取到用户aid
			HttpSession session = request.getSession();
			Integer aid = (Integer)session.getAttribute("aid");
			Admin admin = adminDao.getAdminByAid(aid);
			// 将借阅信息保存到history表
			int row = bookDao.borrowBook(bid, admin);
			System.out.println("增加"+row+"条借阅信息；");
			response.sendRedirect("/book-manager/select.jsp");
		}else {
			//还书
			// 获取借阅记录表
			int hid = Integer.parseInt(request.getParameter("hid"));
			/*
			 * 还书，在管理员和读者页面都有，为了区分设置show字段，show=1表示读者
			 */
			int show = Integer.parseInt(request.getParameter("show"));
			//调用还书方法
			int row = bookDao.backBook(hid);
			System.out.println("还书"+row+"条");
			if(show==1) {
				response.sendRedirect("/book-manager/borrow.jsp");
			}else {
				// 管理员
			}
			
			
		}
		
		
		
	}

}
